package com.bsy.common.decoration

import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import android.view.View
import androidx.annotation.ColorInt
import androidx.recyclerview.widget.RecyclerView

/**
 * 普通条目间距
 * @author Sincerity
 * @date   2023/3/21 8:18
 */
class NormalItemDecoration : RecyclerView.ItemDecoration() {

    private var mLastBottom = false
    private var mIsFirstHead = false
    private val mDivider: ColorDrawable = ColorDrawable()

    fun setBounds(left: Int = 0, top: Int = 0, right: Int = 0, bottom: Int = 0) {
        mDivider.bounds = Rect(left, top, right, bottom)
    }

    fun setColor(@ColorInt color: Int) {
        mDivider.color = color
    }

    /**
     * 是否显示最后一条底部间隔
     */
    fun setLastBottom(lastBottom: Boolean) {
        mLastBottom = lastBottom
    }

    /**
     * 是否显示第一条的所有间隔
     * 用于头部局
     */
    fun setFirstHeadMargin(isFirstHead: Boolean) {
        mIsFirstHead = isFirstHead
    }

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        super.getItemOffsets(outRect, view, parent, state)

        val lastPosition = state.itemCount - 1
        val position = parent.getChildAdapterPosition(view)

        outRect.top = if (position == 0 && mIsFirstHead) 0 else mDivider.bounds.top
        outRect.left = if (position == 0 && mIsFirstHead) 0 else mDivider.bounds.left
        outRect.right = if (position == 0 && mIsFirstHead) 0 else mDivider.bounds.right
        outRect.bottom = if (position == lastPosition && mLastBottom) mDivider.bounds.bottom else 0
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        val childCount = parent.childCount
        for (i in 0 until childCount - 1) {
            val child = parent.getChildAt(i)
            val params = child.layoutParams as RecyclerView.LayoutParams
            val left = parent.paddingLeft + mDivider.bounds.left
            val right = parent.width - parent.paddingRight + mDivider.bounds.right
            val top = child.bottom + params.bottomMargin + mDivider.bounds.top
            val bottom = top + mDivider.bounds.bottom
            mDivider.setBounds(left, top, right, bottom)
            mDivider.draw(c)
        }
    }
}